import React from 'react';
import { IRouteComponentProps, RequestConfig, history } from 'umi';
import StoreContext from '@/context/storeContext';
import Store from '@/store';
import { message } from 'antd';
import { getCookie, setCookie } from './utils/auth';
// import { option } from '@umijs/deps/compiled/yargs';

const baseURL = 'http://111.203.59.61:8060/dev-api';

// let authorization = ""
// let authorization = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjQ2MDUzYTMwLTMwZTgtNGEwMy1hODk5LTUxNTg3NDYwOTZiNyJ9.PybQpQZtzma329Cwea2RMjH6jVVLPcDOpbFUqrAD80vCK4zcis-wZ-lT8VeUwM3Pwm_3zZFfEoZqs9ssvs8n0Q"
let authorization = '';
let errorCode = {
  '400': 'Bad Request',
  '401': 'Unauthorized',
};

export const request: RequestConfig = {
  timeout: 100000,
  errorConfig: {},
  middlewares: [],
  requestInterceptors: [(url, options) => {
    const authorization = getCookie() as string;
    if (!/http/.test(url)) {
      url = baseURL + url;
    }
    let headers = options.headers;
    if (authorization){
      headers = { ...headers, authorization }
    }
    return {
      url,
      options: { ...options, interceptors: true, headers },
    };
  }],

  // 响应拦截器
  responseInterceptors: [
    async (response, options) => {
      let data = { code: 200, msg: '' };
      try {
        data = await response.clone().json();
        // 处理网络错误
        if (response.status !== 200) {
          message.error(response.statusText);
          return response;
        }

        // 处理业务错误
        if (data.code !== 200) {
          message.error(data.msg);
          return response;
        }
      } catch (e:any
        ) {
        message.error(e.message);
        return response;
      }
      return response;
    },
  ],
};

//Store
export function rootContainer(container: React.ReactElement) {
  return React.createElement(
    StoreContext.Provider,
    { value: Store },
    container,
  );
}


// 拦截器
export function onRouteChange({ matchedRoutes, location }: any) {
  let whiteList = ['/login', '/403', '/404'];
  authorization = getCookie() as string;
  if (matchedRoutes.length) {
    document.title = matchedRoutes[matchedRoutes.length - 1].route.title || '';
  }
  // console.log(authorization);

  if (!authorization) {
    // debugger
    if (whiteList.indexOf(location.pathname) !== -1) {
      // debugger
      history.replace( `/login?redirect=${encodeURIComponent(location.pathname)}`);
    }
  }

  // 把首页重定向到/teachers/postSkill
  if(location.pathname === '/'){
    history.replace('/teachers/postSkill')
  }
}